# -*- coding: utf-8 -*-

"""
配置管理器
"""

import yaml
import os


class ConfigManager:
    def __init__(self, config_path="config/config.yaml"):
        """初始化配置管理器"""
        self.config_path = config_path
        self.config = self.load_config()
        
    def load_config(self):
        """加载配置文件"""
        # 确保配置目录存在
        os.makedirs(os.path.dirname(self.config_path), exist_ok=True)
        
        # 如果配置文件不存在，创建默认配置
        if not os.path.exists(self.config_path):
            self.create_default_config()
            
        # 读取配置文件
        with open(self.config_path, 'r', encoding='utf-8') as f:
            return yaml.safe_load(f)
            
    def create_default_config(self):
        """创建默认配置文件"""
        default_config = {
            "game": {
                "default_difficulty": "中等",
                "default_puzzle_size": 4,
                "enable_sound": True,
                "enable_music": True
            },
            "ai": {
                "emotion_analysis_enabled": True,
                "difficulty_prediction_enabled": True,
                "image_generation_theme": "自然风景"
            },
            "display": {
                "window_width": 1000,
                "window_height": 700,
                "fullscreen": False
            },
            "data": {
                "auto_save_progress": True,
                "max_saved_games": 10
            },
            # 添加图片目录配置
            "images": {
                "puzzle_image_directory": ""
            }
        }
        
        with open(self.config_path, 'w', encoding='utf-8') as f:
            yaml.dump(default_config, f, default_flow_style=False, allow_unicode=True)
            
    def get(self, key_path, default=None):
        """
        获取配置值
        
        Args:
            key_path (str): 配置键路径，如 "game.default_difficulty"
            default: 默认值
            
        Returns:
            配置值或默认值
        """
        keys = key_path.split('.')
        value = self.config
        
        try:
            for key in keys:
                value = value[key]
            return value
        except (KeyError, TypeError):
            return default
            
    def set(self, key_path, value):
        """
        设置配置值
        
        Args:
            key_path (str): 配置键路径
            value: 配置值
        """
        keys = key_path.split('.')
        config = self.config
        
        # 导航到倒数第二层
        for key in keys[:-1]:
            if key not in config:
                config[key] = {}
            config = config[key]
            
        # 设置值
        config[keys[-1]] = value
        
        # 保存到文件
        self.save_config()
        
    def save_config(self):
        """保存配置到文件"""
        with open(self.config_path, 'w', encoding='utf-8') as f:
            yaml.dump(self.config, f, default_flow_style=False, allow_unicode=True)